//
//  LZLoginViewController.m
//  laziz_Consumer
//
//  Created by ZhaoDongBo on 2016/10/24.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZLoginViewController.h"
#import "LZRegisterViewController.h"
#import "LZRetrievePasswordViewController.h"
#import "LZMyChangeInfoViewController.h"    //设置密码
#import "LZAreaCodeViewController.h"

#import "LZLoginButtonView.h"
#import "LZLoginTextFieldView.h"
#import "LZTextField.h"

#import "UIViewController+NavigationItemSetting.h"
#import "UIView+Rotation.h"
#import "GVUserDefaults+LZProperties.h"
#import "UIViewController+LZRemoveViewController.h"
#import "NSString+LZRegex.h"
#import "GVUserDefaults+LZLogin.h"

#import "Masonry.h"

#import <MOBFoundation/MOBFoundation.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <ShareSDKExtension/ShareSDK+Extension.h>
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>

#import "LZUserModel.h"
#import "TShareEventHandler.h"

#import "LZRemindView.h"
#import "LZNotificationPresenter.h"
#import "LZUserInfoPresenter.h"
#import "LZAlertView.h"

#import "UIControl+BlocksKit.h"

#import "UIButton+EnlargeEdge.h"
#import "LZActionSheet.h"

@interface LZLoginViewController ()

@property (nonatomic, strong) UIImageView * bgImageView;
@property (nonatomic, strong) UIImageView * logoImageView;
@property (nonatomic, strong) LZLoginTextFieldView * quickLoginView;
@property (nonatomic, strong) LZLoginTextFieldView * phoneLoginView;
@property (nonatomic, strong) LZLoginTextFieldView * mailLoginView;

@property (nonatomic, strong) LZLoginButtonView * loginButtonView;
@property (strong, nonatomic) UIButton *moreLoginModeButton;
@property (nonatomic, weak) LZActionSheet *sheetView;

@property (strong, nonatomic) UIButton *nav_left_back;
@property (strong, nonatomic) UIButton *nav_right_button;
@property (assign, nonatomic) CGFloat lzAlpha;

@property (nonatomic, assign) LoginType loginType;
@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;

@property (nonatomic, strong) NSTimer * timer;      //验证码倒计时
@property (nonatomic, assign) int count;

@end

@implementation LZLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"登录页面";
    
    self.lzAlpha = 0;
    
    [self configBaseData];
    
    //config
    
    [self configViews];
    
    [self changeLoginType:self.loginType];
    
    [self configAutoLayout];
    
    //action
    
    [self fogotPasswrodAction];
    
    [self getVerifiCodeAction];
    
    [self loginViewAction];
        
    [self configNavigationBar];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}
#pragma mark - Private method

//配置navi
- (void)configNavigationBar{
    
    self.nav_left_back = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nav_left_back.frame = CGRectMake(0, 0, 60, 40);
    [self.nav_left_back addTarget:self action:@selector(navbarBackButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image_back = [UIImage imageNamed:@"lz_back"];
    [self.nav_left_back setImage:image_back forState:UIControlStateNormal];
    self.nav_left_back.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(self.nav_left_back.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [self.nav_left_back setLanguageRotaion];
    }
    
    self.nav_right_button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nav_right_button.frame = CGRectMake(0, 0, 80, 40);
    self.nav_right_button.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.nav_right_button setTitle:LZLocalizedString(@"login_for_restaurants", nil) forState:UIControlStateNormal];
    [self.nav_right_button setTitleColor:UIColorFromRGB(0xcccccc, 1) forState:UIControlStateNormal];
    [self.nav_right_button sizeToFit];
    self.nav_right_button.frame = CGRectMake(0, 0, CGRectGetWidth(self.nav_right_button.bounds)+15, self.nav_right_button.titleLabel.intrinsicContentSize.height + 5);
    self.nav_right_button.backgroundColor = UIColorFromRGB(0x000000, 0.2);
    self.nav_right_button.layer.cornerRadius = CGRectGetHeight(self.nav_right_button.bounds)/2.0;
    self.nav_right_button.layer.masksToBounds = YES;
    
    [self.nav_right_button addTarget:self action:@selector(navbarRegisterButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.nav_right_button setEnlargeEdgeWithTop:10 right:0 bottom:10 left:0];
    
    [self hiddenBarNavigationItemSetting:@[self.nav_left_back] type:NAVIGATIONITEMSETTING_LEFT];
    [self hiddenBarNavigationItemSetting:@[self.nav_right_button] type:NAVIGATIONITEMSETTING_RIGHT];
    
    [self lz_setCustomBarAlpha:self.lzAlpha];
}

- (void)configBaseData {
    
    // 根据记录的登录方式显示对应的UI
    if ([GVUserDefaults standardUserDefaults].loginType) {
        NSInteger storeType = [[GVUserDefaults standardUserDefaults].loginType integerValue];
        if (storeType == LoginType_Quick) {
            self.loginType = LoginType_Phone;
        }
        else if (storeType == LoginType_Facebook || storeType == LoginType_Twitter || storeType < 0) {
            self.loginType = LoginType_Quick;
        }
        else {
            self.loginType = storeType;
        }
    }
    else {
        self.loginType = LoginType_Quick; //默认快捷登陆
    }
    
    self.userInfoPresenter = [[LZUserInfoPresenter alloc] init];
}

//配置views
- (void)configViews {
    
    //背景
    [self.view addSubview:self.bgImageView];
    
    //logo
    [self.view addSubview:self.logoImageView];
    
    //快速登录
    [self.view addSubview:self.quickLoginView];
    
    //用户密码登录 -- 手机号登录
    [self.view addSubview:self.phoneLoginView];
    
    //用户密码登录 -- 邮箱登录
    [self.view addSubview:self.mailLoginView];
    
    // 下边按钮的view
    [self.view addSubview:self.loginButtonView];
    
    
    //第三方登录
    WS(weakSelf)
    _moreLoginModeButton = [self createButtonWithTitle:LZLocalizedString(@"login_more_mode", nil) action:^(id sender) {
        if (weakSelf.loginType == LoginType_Quick) {
            [weakSelf.sheetView ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"login_type_phone", nil),LZLocalizedString(@"login_type_email", nil),@"Facebook",@"Twitter"],@[LZLocalizedString(@"cancel", nil)]]];
        }
        else if (weakSelf.loginType == LoginType_Phone) {
            [weakSelf.sheetView ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"login_type_quick", nil),LZLocalizedString(@"login_type_email", nil),@"Facebook",@"Twitter"],@[LZLocalizedString(@"cancel", nil)]]];
        }
        else if (weakSelf.loginType == LoginType_Mail) {
            [weakSelf.sheetView ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"login_type_quick", nil),LZLocalizedString(@"login_type_phone", nil),@"Facebook",@"Twitter"],@[LZLocalizedString(@"cancel", nil)]]];
        }
        
        [weakSelf.sheetView ShowView];
    }];
    [self.view addSubview:self.moreLoginModeButton];
    
}

- (void)configAutoLayout {
    
    GET_SCREEN_SCALE(scale);
    
    [self.logoImageView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(113.0*scale);
        make.centerX.equalTo(0);
    }];
    
    [self.quickLoginView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view.centerY);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(110.0*scale);
    }];
    
    [self.phoneLoginView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view.centerY);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(110.0*scale);
    }];
    
    [self.mailLoginView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view.centerY);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(110.0*scale);
    }];
    
    [self.loginButtonView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.moreLoginModeButton.top).with.offset(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(55.0*scale*3);
    }];
    
    [self.moreLoginModeButton makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(58.0*scale);
    }];
}

/**
 创建一个透明的button
 
 @param xTitle 标题
 @param xAction 事件
 @return .
 */
-(UIButton *)createButtonWithTitle:(NSString *)xTitle action:(void (^)(id sender))xAction{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [button setTitle:xTitle forState:UIControlStateNormal];
    
    button.titleLabel.font = [UIFont systemFontOfSize:17];
    
    [button setTitleColor:UIColorFromRGB(0xff9933, 1) forState:UIControlStateNormal];
    
    [button setBackgroundColor:[UIColor clearColor]];
    
    [button bk_addEventHandler:xAction forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}




- (void)fogotPasswrodAction {
    
    WS(weakSelf);
    
    self.phoneLoginView.buttonAction_TF_Block = ^(LZLOGIN_TF_BUTTON_TAG buttonTag) {
        if (buttonTag == LZLOGIN_TF_BUTTON_TAG_SHOWPASSWORD) {
            DLog(@"忘记密码");
            LZRetrievePasswordViewController * vc = [[LZRetrievePasswordViewController alloc] init];
            vc.type = FindPasswordType_Phone;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
    
    self.mailLoginView.buttonAction_TF_Block = ^(LZLOGIN_TF_BUTTON_TAG buttonTag) {
        if (buttonTag == LZLOGIN_TF_BUTTON_TAG_SHOWPASSWORD) {
            DLog(@"忘记密码");
            LZRetrievePasswordViewController * vc = [[LZRetrievePasswordViewController alloc] init];
            vc.type = FindPasswordType_Mail;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
}

- (void)getVerifiCodeAction {
    
    WS(weakSelf);
    self.quickLoginView.buttonAction_TF_Block = ^(LZLOGIN_TF_BUTTON_TAG buttonTag) {
        
        if (buttonTag == LZLOGIN_TF_BUTTON_TAG_VERIFICCODE) {
            DLog(@"获取验证码");
            [weakSelf getVerifiCode];
        }
    };
}

//切换登陆方式
- (void)changeLoginType:(LoginType)type {
    self.loginType = type;
    if (type == LoginType_Quick) {
        // 快捷登录
        self.quickLoginView.hidden = NO;
        self.phoneLoginView.hidden = YES;
        self.mailLoginView.hidden = YES;
        [self.phoneLoginView hiddenPasswordRecoveryPopView];
    }
    else if (type == LoginType_Phone) {
        // 手机登录(账号密码登录)
        self.quickLoginView.hidden = YES;
        self.phoneLoginView.hidden = NO;
        self.mailLoginView.hidden = YES;
        [self.phoneLoginView showPasswordRecoveryPopView];
        
    }
    else if (type == LoginType_Mail) {
        // 邮箱登录(账号密码登录)
        self.quickLoginView.hidden = YES;
        self.phoneLoginView.hidden = YES;
        self.mailLoginView.hidden = NO;
        [self.phoneLoginView showPasswordRecoveryPopView];
    }
}

#pragma mark 获取验证码
- (void)getVerifiCode {
    
    if (self.quickLoginView.mobileNumTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"login_enter_mobile", @"")];
        return;
    }
    //验证码类型（1注册，2快捷登录，3身份验证，4绑定手机）
    NSString * mobileStr = [NSString stringWithFormat:@"%@%@",
                            self.quickLoginView.areaCodeTextField.text,
                            self.quickLoginView.mobileNumTextField.text];
//    if (mobileStr.length < 11) {
//        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
//                         andContent:LZLocalizedString(@"enter_invalid_mobile", @"")];
//        return;
//    }
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    WS(weakSelf);
    
    [self.userInfoPresenter userGetVerificationCodeType:@"2"
                                            andPhoneNum:mobileStr
                                              onSuccess:^(id data) {
                                                  
                                                  DLog(@"快捷登录 -（2）- 获取验证码:%@", data);
                                                  
                                                  [weakSelf stopLoadingViewForView:weakSelf.view];
                                                  
                                                  //显示倒计时
                                                  [weakSelf startTimer];
                                                  
                                              } onFail:^(NSString *fail) {
                                                  DLog(@"%@", fail);
                                                  [weakSelf stopLoadingViewForView:weakSelf.view];

                                                  if ([fail isEqualToString:@"9999999"]) {
                                                      
//                                                      [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
//                                                                       andContent:LZLocalizedString(@"send_code_maxnum_remind", nil)];
                                                      LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"send_code_maxnum_remind", nil)
                                                                                                       andImage:[UIImage imageNamed:@"error_image"]
                                                                                              cancelButtonTitle:LZLocalizedString(@"confirm", nil)
                                                                                              otherButtonTitles:nil, nil];
                                                      [alert show];
                                                  }
                                                  else {
                                                      
                                                      [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                                       andContent:LZLocalizedString(@"vificode_failed", nil)];
                                                  }

                                              }];
}

#pragma mark 用户密码登陆
- (void)accountTypeLogin {
    
    NSString * userName = nil;
    NSString * passwordStr = nil;
    
    if (self.loginType == LoginType_Phone) {
       
        userName = [NSString stringWithFormat:@"%@%@", self.phoneLoginView.areaCodeTextField.text, self.phoneLoginView.mobileNumTextField.text];
        passwordStr = self.phoneLoginView.passwordTextField.text;
        
        if (self.phoneLoginView.mobileNumTextField.text.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"login_enter_mobile", @"")];
            return;
        }
    }
    else if (self.loginType == LoginType_Mail) {
        userName = self.mailLoginView.mobileNumTextField.text;
        passwordStr = self.mailLoginView.passwordTextField.text;
        
        if (userName.length<=0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"login_enter_email", nil)];
            return;
        }
        else if (![userName isEmailAddress]) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"invalid_email_remind", nil)];
            return;
        }
    }
    
    if (passwordStr.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"enter_password", @"")];
        return;
    } else if (passwordStr.length > 0 && passwordStr.length < 6) {
        if (self.loginType == LoginType_Phone) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"account_mobile_failed", nil)];
        }
        else if (self.loginType == LoginType_Mail) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"account_email_failed", nil)];
        }        
        return;
    }
    
    DLog(@"账户登录：/r userName:%@ /r passwordStr:%@", userName, passwordStr);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    WS(weakSelf);
    [self.userInfoPresenter userLoginCellPhone:userName
                       andPasswordOrVerifiCode:passwordStr
                                  andLoginType:1
                                     onSuccess:^(id data) {
                                         
                                         DLog(@"账户登录：%@", data);
                                         
                                         [weakSelf stopLoadingViewForView:weakSelf.view];
                                         
                                         // 记录登录方式，用于下次登录时显示对应的UI
                                         [GVUserDefaults standardUserDefaults].loginType = [NSString stringWithFormat:@"%ld",(long)weakSelf.loginType];
                                         
                                         //保存token
                                         [[GVUserDefaults standardUserDefaults] setUserToken:[[data objectForKey:@"data"] objectForKey:@"token"]];
                                         //保存用户名密码
                                         [[GVUserDefaults standardUserDefaults] setUserId:[[data objectForKey:@"data"] objectForKey:@"userId"]];
                                         //通知设置id
                                         [LZNotificationPresenter setNotificationAlias:[[data objectForKey:@"data"] objectForKey:@"userId"]];
                                                                                  
                                         //更新用户信息
                                         [[LZUserModel Instance] updateUserInfoIfNeeded];
                                         
                                         //跳转
                                         [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                                         
                                     } onFail:^(NSString *fail) {
                                         
                                         DLog(@"%@", fail);
                                         
                                         [weakSelf stopLoadingViewForView:weakSelf.view];
                                         
                                         if ([fail isEqualToString:@"0500031"]) { //0500031 该用户已被停用，请联系管理员
                                             LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"mag_account_stopstate", nil)
                                                                                              andImage:nil
                                                                                     cancelButtonTitle:LZLocalizedString(@"cancel", nil)
                                                                                     otherButtonTitles:nil, nil];
                                             [alert show];
                                         }
                                         else if ([fail isEqualToString:@"0500002"]) { //0500002 用户名或密码错误，登录失败
                                             if (self.loginType == LoginType_Phone) {
                                                 [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                                  andContent:LZLocalizedString(@"account_mobile_failed", nil)];
                                             }
                                             else if (self.loginType == LoginType_Mail) {
                                                 [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                                  andContent:LZLocalizedString(@"account_email_failed", nil)];
                                             }
                                         }
                                         else {
                                             [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                              andContent:LZLocalizedString(@"login_failed", nil)];
                                         }
                                     }];
}

#pragma mark 快捷登录
- (void)quickTypeLogin {
    
    if (self.quickLoginView.mobileNumTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"login_enter_mobile", @"")];
        return;
    }
    
    NSString * userName = [NSString stringWithFormat:@"%@%@",
                           self.quickLoginView.areaCodeTextField.text,
                           self.quickLoginView.mobileNumTextField.text];
    
    NSString * passwordStr = self.quickLoginView.verificCodeTextField.text;
    
    if (userName.length < 11) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"enter_invalid_mobile", @"")];
        return;
    }
    
    if (passwordStr.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"login_enter_verifi_code", @"")];
        return;
    }
    
    DLog(@"快捷登录：/r userName:%@ /r passwordStr=%@ /r", userName, passwordStr);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    WS(weakSelf);
    [self.userInfoPresenter userLoginCellPhone:userName
                       andPasswordOrVerifiCode:passwordStr
                                  andLoginType:2
                                     onSuccess:^(id data) {
                                         
                                         [weakSelf stopLoadingViewForView:weakSelf.view];
                                         
                                         DLog(@"快捷登录：%@", data);
                                         
                                         // 记录登录方式，用于下次登录时显示对应的UI
                                         [GVUserDefaults standardUserDefaults].loginType = [NSString stringWithFormat:@"%ld",(long)weakSelf.loginType];
                                         
                                         // 记录选择的区号
                                         [GVUserDefaults standardUserDefaults].loginAreaCode = weakSelf.quickLoginView.areaCodeTextField.text;
                                         
                                         [[GVUserDefaults standardUserDefaults] setUserToken:[[data objectForKey:@"data"] objectForKey:@"token"]];
                                         [LZNotificationPresenter setNotificationAlias:[[data objectForKey:@"data"] objectForKey:@"userId"]];
                                         [[GVUserDefaults standardUserDefaults] setUserId:[[data objectForKey:@"data"] objectForKey:@"userId"]];

                                         //更新用户信息
                                         [[LZUserModel Instance] updateUserInfoIfNeeded];
                                         
                                         if([[[data objectForKey:@"data"] objectForKey:@"isHavePassword"] boolValue] == NO) {
                                             //如果没有设置密码，跳转设置密码页面
                                             LZMyChangeInfoViewController *vc = [[LZMyChangeInfoViewController alloc] init];
                                             vc.moblieNumber = userName;
                                             vc.type = LZ_MYCHANGEINFO_TYPE_SETPASSWORD;
                                             vc.sourceViewType = SourceViewType_LoginVC;
                                             [weakSelf.navigationController pushViewController:vc animated:YES];
                                             
                                             [weakSelf lz_removeSelfFromNavigation];
                                             
                                         }
                                         else {
                                             //否则跳转个人页面
                                             [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                                         }
                                         
                                     } onFail:^(NSString *fail) {
                                         DLog(@"%@", fail);
                                         [weakSelf stopLoadingViewForView:weakSelf.view];
                                         
                                         if ([fail isEqualToString:@"0400001"] || [fail isEqualToString:@"0100010"] || [fail isEqualToString:@"0500001"]) { //0100010 验证码错误！
                                             [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                              andContent:LZLocalizedString(@"enter_invalid_verifi", nil)];
                                         }
                                         else if ([fail isEqualToString:@"0500031"]) { //0500031 该用户已被停用，请联系管理员
                                             LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"mag_account_stopstate", nil)
                                                                                              andImage:nil
                                                                                     cancelButtonTitle:LZLocalizedString(@"cancel", nil)
                                                                                     otherButtonTitles:nil, nil];
                                             [alert show];
                                         }
                                         else {
                                             [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                              andContent:LZLocalizedString(@"login_failed", nil)];
                                         }
                                     }];
}

- (void)loginViewAction {
    
    WS(weakSelf)
    
    self.loginButtonView.buttonActionBlock = ^(LZLOGINBUTTONTYPE_TAG buttonTag) {
        
        
        switch (buttonTag) {
            case LZLOGINBUTTONTYPE_TAG_LOGINNOW:
            {
                //todo 登录用对应的type
                
                if (weakSelf.loginType == LoginType_Quick) {   // 快捷登录
                    [weakSelf quickTypeLogin];
                }
                 else if (weakSelf.loginType == LoginType_Mail || weakSelf.loginType == LoginType_Phone) { //用户密码登录
                     [weakSelf accountTypeLogin];
                 }
            }
                break;
            case LZLOGINBUTTONTYPE_TAG_REGISTER:
            {
                //todo  注册用对应的type

                LZRegisterViewController * vc = [[LZRegisterViewController alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                [weakSelf.phoneLoginView hiddenPasswordRecoveryPopView];
            }
                break;
                default:
                break;
        }
    };
}

#pragma mark - Event

- (void)startTimer {
    
    self.quickLoginView.countdownLabel.text = @"60s";
    [self.timer invalidate];
    self.count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(updateTime)
                                                userInfo:nil
                                                 repeats:YES];
    
    self.quickLoginView.countdownLabel.hidden = NO;
    self.quickLoginView.verificCodeButton.hidden = YES;
}

- (void)stopTimer {
    [self.timer invalidate];
    self.quickLoginView.countdownLabel.hidden = YES;
    self.quickLoginView.verificCodeButton.hidden = NO;
}

- (void)updateTime
{
    self.count ++;
    if (self.count >= 60)
    {
        [self stopTimer];
        return;
    }
    
    self.quickLoginView.countdownLabel.text = [NSString stringWithFormat:@"%is", 60-self.count];
    
    if (self.count == 60) {
        self.quickLoginView.countdownLabel.hidden = YES;
        self.quickLoginView.verificCodeButton.hidden = NO;
    }
}

- (void)navbarBackButtonClickAction:(UIButton*)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)navbarRegisterButtonClickAction:(UIButton*)sender {
    DLog(@"跳转 appStore 按钮");
    [self.phoneLoginView hiddenPasswordRecoveryPopView];

    [TShareEventHandler jumpToAppstoreForMerchantApp];
    
}

#pragma mark 第三方登录
- (void)thirdPartLogin:(SSDKPlatformType)type {
    
    WS(weakSelf);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    [SSDKAuthViewStyle setCancelButtonLabelColor:UIColorFromRGB(0x666666, 1)];
    [SSDKAuthViewStyle setTitle:@"Authorize"];
    [SSDKAuthViewStyle setTitleColor:UIColorFromRGB(0x333333, 1)];
    [SSDKAuthViewStyle setStatusBarStyle:UIStatusBarStyleDefault];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    
    [ShareSDK authorize:type
               settings:nil
         onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
         
         switch (state) {
             case SSDKResponseStateSuccess:
             {
                 DLog(@"授权成功 %@", user);
                 
                 NSMutableDictionary * param_Dict = [NSMutableDictionary dictionary];
                 
                 [param_Dict setObject:user.uid                 forKey:@"userName"];
                 [param_Dict setObject:user.icon                forKey:@"userPhoto"];
                 [param_Dict setObject:user.nickname            forKey:@"nickName"];
                 [param_Dict setObject:user.credential.token    forKey:@"partyKey"];
                 
                 if (type == SSDKPlatformTypeFacebook) {
                     [param_Dict setObject:@"1"                forKey:@"partyType"];
                 } else {
                     [param_Dict setObject:@"2"                forKey:@"partyType"];
                 }
                 
                 DLog(@"第三方登陆获取的信息：%@", param_Dict);
                 
                 [weakSelf.userInfoPresenter userThirdPartLoginCellPhone:param_Dict onSuccess:^(id data) {
                     
                     [weakSelf stopLoadingViewForView:weakSelf.view];
                     
                     DLog(@"第三方登录：%@", data);
                     if (type == SSDKPlatformTypeFacebook) {
                         weakSelf.loginType = LoginType_Facebook;
                     }
                     else if (type == SSDKPlatformTypeTwitter) {
                         weakSelf.loginType = LoginType_Twitter;
                     }
                     
                     // 记录登录方式，用于下次登录时显示对应的UI
                     [GVUserDefaults standardUserDefaults].loginType = [NSString stringWithFormat:@"%ld",(long)weakSelf.loginType];
                     
                     //存储token
                     [[GVUserDefaults standardUserDefaults] setUserToken:[[data objectForKey:@"data"] objectForKey:@"token"]];
                     [LZNotificationPresenter setNotificationAlias:[[data objectForKey:@"data"] objectForKey:@"userId"]];
                     [[GVUserDefaults standardUserDefaults] setUserId:[[data objectForKey:@"data"] objectForKey:@"userId"]];
                     //更新用户信息
                     [[LZUserModel Instance] updateUserInfoIfNeeded];
                     
                     //授权成功，跳转个人页面
                     [weakSelf.navigationController popViewControllerAnimated:YES];
                     
                 } onFail:^(NSString *fail) {
                     [weakSelf stopLoadingViewForView:weakSelf.view];
                     [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                      andContent:LZLocalizedString(@"login_failed", nil)];
                     DLog(@"%@", fail);
                 }];
                 
                 break;
             }
             case SSDKResponseStateFail:
             {
                 [weakSelf stopLoadingViewForView:weakSelf.view];
                 DLog(@"授权失败 %@", error);
                 break;
             }
             case SSDKResponseStateCancel:
             {
                 [weakSelf stopLoadingViewForView:weakSelf.view];
                 DLog(@"授权取消");
                 break;
             }
             default:
                 break;
         }
     }];
}

#pragma mark - Setter/Getter

- (UIImageView *)bgImageView {
    
    if (_bgImageView == nil) {
        _bgImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
        _bgImageView.image = [UIImage imageNamed:@"lz_bg"];
    }
    
    return _bgImageView;
}

- (UIImageView *)logoImageView {
    if (_logoImageView == nil) {
        _logoImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lz_logo_white"]];
    }
    return _logoImageView;
}

// 快捷登录的UI
- (LZLoginTextFieldView *)quickLoginView {
    
    if (_quickLoginView == nil) {
        _quickLoginView = [[LZLoginTextFieldView alloc] initWithPage:LZLOGIN_TF_TYPE_PAGE_FASTLOGIN];
        
        WS(weakSelf);
        _quickLoginView.clickAreaCodeTextFieldBlock = ^(UILabel *label) {
            LZAreaCodeViewController *vc = [[LZAreaCodeViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
            vc.SelectedAreaCodeBlock = ^(NSString *areaCode) {
                label.text = areaCode;
            };
        };
    }
    
    return _quickLoginView;
}

// 手机号登录的UI
- (LZLoginTextFieldView *)phoneLoginView {
    
    if (_phoneLoginView == nil) {
        _phoneLoginView = [[LZLoginTextFieldView alloc] initWithPage:LZLOGIN_TF_TYPE_PAGE_PHONELOGIN];
        
        WS(weakSelf);
        _phoneLoginView.clickAreaCodeTextFieldBlock = ^(UILabel *label) {
            LZAreaCodeViewController *vc = [[LZAreaCodeViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
            vc.SelectedAreaCodeBlock = ^(NSString *areaCode) {
                label.text = areaCode;
            };
        };
    }    
    
    return _phoneLoginView;
}

// 邮箱登录的UI
- (LZLoginTextFieldView *)mailLoginView {
    if (_mailLoginView == nil) {
        _mailLoginView = [[LZLoginTextFieldView alloc] initWithPage:LZLOGIN_TF_TYPE_PAGE_MAILLOGIN];
    }
    
    return _mailLoginView;
}

- (LZLoginButtonView *)loginButtonView {
    
    if (_loginButtonView == nil) {
        _loginButtonView = [[LZLoginButtonView alloc] initWithPage:LZLOGINBUTTONTYPE_PAGE_LOGIN];
    }
    
    return _loginButtonView;
}

- (LZActionSheet*)sheetView {
    if (_sheetView) {
        return _sheetView;
    }
    
    LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:self.navigationController.view.bounds];
    _sheetView = sheet;
    [self.navigationController.view addSubview:_sheetView];
    
    WS(weakSelf)
    _sheetView.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
        if (indexPath.section == 0) {
            switch (indexPath.row) {
                case 0:
                {
                    // todo  -- Mobile phone and password -- or -- quick login --
                    if (weakSelf.loginType == LoginType_Quick) {
                        [weakSelf changeLoginType:LoginType_Phone];
                    }
                    else {
                        [weakSelf changeLoginType:LoginType_Quick];
                    }
                }
                    break;
                case 1:
                {
                    // todo e-Mail and password
                    if (weakSelf.loginType == LoginType_Quick || weakSelf.loginType == LoginType_Phone) {
                        [weakSelf changeLoginType:LoginType_Mail];
                    }
                    else if (weakSelf.loginType == LoginType_Mail) {
                        [weakSelf changeLoginType:LoginType_Phone];
                    }
                }
                    break;
                case 2:
                {
                    // todo Facebook
                    [weakSelf thirdPartLogin:SSDKPlatformTypeFacebook];
                }
                    break;
                case 3:
                {
                    // todo Twitter
                    [weakSelf thirdPartLogin:SSDKPlatformTypeTwitter];
                }
                    break;
                    
                default:
                    break;
            }
        }
    };
    
    return _sheetView;
}

@end
